<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Http\Services\ASEService;
use App\Http\Services\RSAService;
use App\Models\Card;
use App\Models\City;
use App\Models\Company;
use App\Models\CompanyCity;
use App\Models\Goods;
use App\Models\Order;
use App\Utils\AES;
use App\Utils\RSA;
use Carbon\Carbon;
use http\Env\Response;
use Illuminate\Http\Request;

class RongshuController extends Controller
{
    public function test() {
        return view('test');
    }

    // 订单预约入口
    public function enterance(Request $request) {
        $passId = $request->id;
        $id = ASEService::decrypt($passId);

        if ($id === false) {
            return response('编号异常,请检查');
        }

        $order = Order::where('sn', $id)->first();
        if (!$order)
        {
            return response('订单不存在');
        }

        $host = config('app.url');
        $outTime = (time() - strtotime($order->created_at)) > 180 * 24 * 60 * 60;
        if ($order->shop || $outTime) {
            // 已经预约 跳转到订单完成页面
            $url = $host . '/makephoto/index.html#pages/order/order-finish?sn='.$passId;
        } else {
            // 还未预约 跳转到前端首页
            $url = $host . '/makephoto/index.html#pages/order/order-appointment?sn='.$passId;
        }
        echo "<script>location.replace('{$url}')</script>";
        exit;
    }

    /**
     * 根据产品获取城市区域
     */
    public function cities(Request $request) {

        $data       = self::decrypt($request);
        $productNo  = $data['productNo'];
        if (isset($data['cityType'])) {
            $cityType = $data['cityType'];
        } else {
            $gInfo = self::parse_goods_sn($productNo);
            $productNo = $gInfo['goods'];
            $cityType = $gInfo['city'];
        }

        $goods      = Goods::where('sn', $productNo)->first();
        if (!$goods) {
            return self::fail1('000002', '产品不存在');
        }

        $company    = $goods->company;
        $cities     = CompanyCity::cities($company, $cityType, $productNo);

        return self::success1(['data' => $cities]);
    }

    private static function parse_goods_sn($productNo) {
        $pos = strlen($productNo) - 2;
        $cityType   = substr($productNo, $pos + 1);
        $productNo  = substr($productNo, 0, $pos);
        return ['goods'=> $productNo, 'city' => $cityType];
    }

    /**
     * @param Request $request
     * @return array
     */
    public function order_create(Request $request) {
        $data = self::decrypt($request);

        // 检查是否重复提交订单
        if (Order::where('sip_sn', $data['sipOrderNo'])->first()) {
            return self::fail1('000001', '订单重复提交');
        }

        // 检查产品是否存在
        $gInfo = self::parse_goods_sn($data['productNo']);
        $goods = Goods::where('sn', $gInfo['goods'])->first();
        if (!$goods) {
            return self::fail1('000002', '产品不存在');
        }

        // 生成一个卡号
        while (true) {
            $card = str_rand(8);
            if (!Card::where('code', $card)->first()) {
                break;
            }
        }

        $cityId = $data['cityId'];
        $cityInfo = City::find($cityId);
        if ($cityInfo->city_id != $cityId) {
            $cityId = $cityInfo->city_id;
        }
        $orderSn = order_sn();
        $order = Order::create([
            'user_id'   => $data['userId'],
            // 'user_name' => $data['userName'],
            'sn'        => $orderSn,
            'sn_for_company' => $orderSn,
            'sip_sn'=> $data['sipOrderNo'],
            'goods' => $goods->id,
            'mobile'=> $data['mobileNo'],
            'city'  => $cityId,
            'company'=>$goods->company,
            'card'  => Order::create_card()
        ]);

        $passID = ASEService::encrypt($order->sn);
        $data = [
            'userLink'      => url('order/enterance') . '?id='.$passID,
            'sipOrderNo'    => $data['sipOrderNo'],
            'venderOrderNo' => (string)$order->sn,
            'userStatus'    => '0'
        ];

        return self::success1($data);
    }

    /**
     * 退款检查
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function refund_check(Request $request) {
        $data = self::decrypt($request);
        $order = Order::where('sip_sn', $data['sipOrderNo'])->first();

        if (!$order) {
            return self::fail1("000010", "订单不存在");
        }

        if ($order->time) { // 已经预约
            return self::fail1("000001", "已预约，无法退款");
        } else {
            return self::success1();
        }
    }

    /**
     * 退款申请
     * @param Request $request
     */
    public function refund_apply(Request $request) {
        $data = self::decrypt($request);
        $order = Order::where('sip_sn', $data['sipOrderNo'])->first();

        if (!$order) {
            return self::fail1("000010", "订单不存在");
        }

        if ($order->time) {
            return self::fail1("000001", '已预约，无法退款');
        }

        $order->refund = 1;
        $order->refund_time = date('Y-m-d H:i:s');
        $order->save();

        return self::success1();
    }

    /**
     * 退款确认
     * @param Request $request
     */
    public function refund_confirm(Request $request) {
        $data = self::decrypt($request);
        $order = Order::where('sip_sn', $data['sipOrderNo'])->first();
        if (!$order) {
            return self::fail1("000010", "订单不存在");
        }

        $order->refund = 2;
        $order->refund_time = datetime();
        $order->status = Order::STATUS_REFUND_OK;
        $order->save();
        return self::success1();
    }

    private static function encrypt($data) {
        $rsa = new RSA(config('rsa.path'));

        // 转json
        $jsonData = json_encode($data);

        // 加密
        $enJson = $rsa->pubEncrypt($jsonData);

        // 加签
        $sign = $rsa->priSign($jsonData);

        return "data=" . $enJson . "&sign=" . $sign;
    }

    /**
     * 解密 用同铸的私钥对数据进行解密
     * 验签 用sip的公钥进行延签
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    private static function decrypt(Request $request) {

        if (!config('rsa.in_open')) { // 未开启RSA加密
            return $request->all();
        }

        $data = str_replace(" ", "+", $request->data);
        $sign = str_replace(" ", "+", $request->sign);

        // 解密
        $deData = RSAService::tz_private_decrypt($data);
        if ($deData == '') {
            throw new \Exception("数据解密失败");
        }
        // 验签
        $signCheck = RSAService::tz_sign($sign);
        if ($signCheck) {
            return \GuzzleHttp\json_decode($deData, true);
        } else {

            throw new \Exception("数据签名验证失败");
        }
    }

    /**
     * 订单进度通知
     */
    static function order_progress_notify($orderId){

    }
    /**
     * 订单状态通知
     */
    private static function order_apply() {

    }

    public static function json1($code, $msg, $data = null) {
        if ($data) {
            $data['resCode'] = $code;
            $data['resMsg'] = $msg;
        } else {
            $data = ['resCode' => $code, 'resMsg' => $msg];
        }

        if (!config('rsa.out_open')) {
            // $data['code'] = $data;
            return response()->json($data);
        } else {
            $jsonData   = json_encode($data);
            $secretData = RSAService::sip_public_encrypt($jsonData); // 荣数的公钥加密
            $sign       = RSAService::tz_sign($jsonData);
            $data       = "data=".$secretData."&sign=".$sign;
            return response()->json($data);
        }
    }

    public static function success1($data = null) {
        return self::json1("000000", "success", $data);
    }

    public static function fail1($code, $msg) {
        return self::json1($code, $msg);
    }

}
